<?php

namespace app\modules\prod\controllers;


use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\Functions;
use app\common\SystemEvent;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use app\models\ProdSpec;
use app\models\ProdInst;
use app\models\Cust;
use app\models\CustExternalAttr;
use app\models\ProdInstSearch;
use app\models\ProdAttrSpecRela;
use app\models\ProdAttrInst;
use app\models\UploadForm;
use app\models\Image;
use app\models\Staff;
use app\models\StaffRelaSearch;
use app\models\StaffRela;


use app\models\Order;
use app\models\OrderResumes;
use app\models\OrderSearch;
use app\models\OrderType;
use app\models\Domain;

use app\models\CustomTableView;
//use kartik\file\FileInput;
use yii\web\UploadedFile;


use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;

class StaffMangerController extends Controller
{
    public $enableCsrfValidation = false;
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}

	// 江南片区
    public function actionSouth()
    {
        return $this->actionClassify(10001,199);
    }

    // 江北片区
    public function actionNorth()
    {
        return $this->actionClassify(10001,200);

    }

    // 商圈管理
    public function actionCirclemng()
    {
        return $this->actionClassify(10003);
    }

	// 楼盘管理
    public function actionProjectsmng()
    {
       return $this->actionClassify(10004);
    }

	// 大楼管理
    public function actionBuildingmng()
    {
        return $this->actionClassify(10001);
    }

    // 房间管理(独立房源)
    public function actionRoomsmng()
    {
        return $this->actionClassify(10002,null,null,null,2,-1);
    }

    // 我的房源)
    public function actionGonyoumng()
    {

        $id=Yii::$app->user->id;
        return $this->actionClassify(10002,null,null,null,2,$id);
//        $lendedAreas=789;
//        return $this->render('view3', [
//            'regions' => $lendedAreas ]);

    }




//     public function actionIndex($q)
//    {
//        $query = Region::find();
//        $pagination = new Pagination([
//            'defaultPageSize' => 5,
//            'totalCount' => $query->count(),
//        ]);
//        $regions = $query->orderBy('region_type_id')->offset($pagination->offset)->limit($pagination->limit)->all();
//        return $this->render('index', ['pagination' => $pagination ,
//        'regions' => $regions ]);
//
//    }


    public function actionSeachorderstaff($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = Staff::find()
            ->select('user_id as id, staff_name as text')
            ->where(['staff_type_id'=>'1'])
            ->andFilterWhere(['like', 'staff_name', $q])
            ->limit(12)
            ->asArray()
            ->all();
        $publicSatff=[];
        $publicSatff['id'] = -1;
        $publicSatff['text'] = '进入公盘';
        $data[] = $publicSatff;
        $out['results'] = array_values($data);

        return $out;
    }


    public function actionSeachorderstaff2($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = Staff::find()
            ->select('user_id as id, staff_name as text')
            ->where(['staff_type_id'=>'1'])
            ->andFilterWhere(['like', 'staff_name', $q])
            ->limit(12)
            ->asArray()
            ->all();
        $publicSatff=[];
        $publicSatff['id'] = -1;
        $publicSatff['text'] = '进入公盘';
        $data[] = $publicSatff;
        $out['results'] = array_values($data);

        return $out;
    }

    public function actionSeachcust($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = Cust::find()
            ->select('id, cust_name as text')
            ->where(['state'=>'301'])
            ->andFilterWhere(['like', 'cust_name', $q])
            ->limit(12)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionSeachprodinst($q, $parent_prod_spec_id=null)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        if (!$parent_prod_spec_id)
        {
            $parent_prod_spec_id = 10001;
        }


        $data = ProdInst::find()
            ->select('id, prod_name as text')
            ->where(['prod_spec_id'=>$parent_prod_spec_id])
            ->andFilterWhere(['like', 'prod_name', $q])
            ->limit(12)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionView($id=null, $prod_spec_id=null, $prod_spec_name = null)
    {
        $topShowCnt = 0;
        $topShowss = [];

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;

        $model = $this->getProdInst($id);

        // 获取到对应图片的全部URL
        $p1 = $this->getProdAttrInstByID($id );


        //  查询所有该产品的特性值规格，主要用来取名称
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);
        $attrSpecNames = [];
        foreach ($attrSpecs as $attrSpec)
        {

            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;

        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        // 组织top_show的内容

        $topShows[$topShowCnt]['field_name']    = '创建用户';
        $topShows[$topShowCnt]['field_values']  = $model->users->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建时间';
        $topShows[$topShowCnt]['field_values']  = $model->create_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '修改用户';
        $topShows[$topShowCnt]['field_values']  = $model->modifyUsers->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '修改时间';
        $topShows[$topShowCnt]['field_values']  = $model->modify_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '状态';
        $topShows[$topShowCnt]['field_values']  = Functions::getDomainsName('prod','floor.state',$model->state);
        $topShowCnt++;


        return $this->renderAjax('modalview',
            ['model' => $model,
                'p1' =>$p1,
                'attrSpecNames' => $attrSpecNames,
                'topShows' => $topShows,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    /*
    public function actionView($id=null, $prod_spec_id=null, $prod_spec_name = null)
    {
        $topShowCnt = 0;
        $topShowss = [];

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;

        $model = $this->getProdInst($id);

        // 获取到对应图片的全部URL
        $p1 = $this->getProdAttrInstByID($id );
        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
     Yii::trace($p1);

        //  查询所有该产品的特性值规格，主要用来取名称
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);
        $attrSpecNames = [];
        foreach ($attrSpecs as $attrSpec)
        {
//            Yii::trace($attrSpec );
//            Yii::trace($attrSpec->attrSpecs );
//            Yii::trace($attrSpec->attrSpecs->id );
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;

//            foreach ($attrSpec as $attrSpecs)
//            {
//                Yii::trace($attrSpecs );
//                $attrSpecNames[$attrSpecs->attrSpecs->id]['name'] = $attrSpecs->attrSpecs->attr_spec_name;
//            }
        //    $attrSpecNames[$attrSpec->attrSpecs->id]['name'] = $attrSpec->attrSpecs->attr_spec_name;
           // break;
        }

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//        Yii::trace($attrSpecs );
//
//        Yii::trace($attrSpecNames);
//            Yii::trace($newProdInst->attrSpec );

        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        // 组织top_show的内容
//        $topShows[$topShowCnt]['field_name']    = '详细地址';
//        $topShows[$topShowCnt]['field_values']  = $model->users->username;
//        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建用户';
        $topShows[$topShowCnt]['field_values']  = $model->users->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建时间';
        $topShows[$topShowCnt]['field_values']  = $model->create_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '修改用户';
        $topShows[$topShowCnt]['field_values']  = $model->modifyUsers->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '修改时间';
        $topShows[$topShowCnt]['field_values']  = $model->modify_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '状态';
        $topShows[$topShowCnt]['field_values']  = $model->state;
        $topShowCnt++;


        return $this->render('view',
            ['model' => $model,
                'p1' =>$p1,
                'attrSpecNames' => $attrSpecNames,
                'topShows' => $topShows,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }
*/

    public function update($id=null, $prod_spec_id=null, $prod_spec_name = null)
    {

    }

    public function actionUpdatemodal($id=null, $prod_spec_id=null, $prod_spec_name = null, $last_url=null)
    {
        // 初始化最重要的产品实例字段
        $postModel   = new ProdInst();

        // 初始化全部的图片
        $uploadModel = new UploadForm();



        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;
        //ProdSpec::find()->select(['spec_name'])->where(['id' => $prod_spec_id])->one();

        //取到产品实例数据

        //  $model = $this->findModel($id);
        $model = new ProdInst();

        $query3 = ProdInst::find()->alias('a');
        if ($prod_spec_id==10002)
        {
            $query3->joinWith('parentProdInsts  AS g');

        }
        $query3->joinWith('regions  AS b');
        $query3->joinWith('parentRegions  AS c');


        //$query3->joinWith('superParentRegions  AS f');
        $query3->joinWith('prodAttrInsts  AS e');
        //  $query3->joinWith('useCusts  AS f');
        $query3->where(['a.id' => $id ]);

        $model2 = $query3->all();

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//           Yii::trace($model2);

        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];


        $p1 = $this->getProdAttrInstByID($id );


        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;
        }

        foreach ( $model2 as $prodinst)
        {
//            Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&");
//
//            Yii::trace($prodinst->parentProdInsts);
//            Yii::trace($prodinst);
            $model->own_cust_id     = $prodinst->own_cust_id;
            $model->use_cust_id     = $prodinst->use_cust_id;
            $model->parent_id     = $prodinst->parent_id;
            $model->id             = $prodinst->id ;
            $model->prod_spec_id = $prodinst->prod_spec_id ;
            $model->prod_name    = $prodinst->prod_name ;
            $model->province     = $prodinst->parentRegions->parent_region_id;
            $model->city          = $prodinst->parentRegions->id;
            $model->areas         = $prodinst->areas ;
            $model->region_id       = $prodinst->region_id ;
            $model->state       = $prodinst->state ;
            if ($prodinst->parentProdInsts)
            {
                $model->parentProdName = $prodinst->parentProdInsts->prod_name;
                Yii::trace($model->parentProdName);
            }

            $model->localProdAttrsInsts=[];
            foreach($prodinst->prodAttrInsts as $prodAttrInst)
            {
                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
            }


           // $model->useCusts = $prodinst->useCusts;

            //$model->attrSpec = $prodinst->prodAttrInsts ;

            //Yii::trace($prodinst->attrSpec);

            // Yii::trace($model->attrSpec);
            //    Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&model->attrSpec&&&&&&&&&&&&&&&&&&&&&&&&");
            break;
        }



        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {
            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;

            //更新prod_inst
            $this->insertOrUpdateToProdInstTable($postModel, $model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
            return Yii::$app->request->getReferrer();
            //   return $this->redirect(['classify','prod_spec_id' =>$prod_spec_id]);
        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        //$regionList      = $query2->orderBy('id')->all();


        //获取父级产品规格，如果没有返回0
        $parent_prod_spec_id = $this->getParentProdSpecID($prod_spec_id);

        // 获取产品状态
        $domainTypes   = Functions::getDomains('prod', 'floor.state');


        return $this->render('update',
            [
                'domainTypes' => $domainTypes,
                'parent_prod_spec_id' => $parent_prod_spec_id,
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }
    /*
     *  更新内容
     * */
    public function actionUpdate($id=null, $prod_spec_id=null, $prod_spec_name = null,$last_url=null)
    {
//
//        $id             = Yii::$app->request->post('id', $id);
//        $prod_spec_id   = Yii::$app->request->post('prod_spec_id', $prod_spec_id);
//        $prod_spec_name = Yii::$app->request->post('prod_spec_name', $prod_spec_name);
//        $last_url       = Yii::$app->request->post('last_url', $last_url);


//
//        Yii::trace("**********************last_url========");
//       Yii::trace($last_url);


        // 初始化最重要的产品实例字段
        $postModel   = new ProdInst();

        // 初始化全部的图片
        $uploadModel = new UploadForm();



        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;
        //ProdSpec::find()->select(['spec_name'])->where(['id' => $prod_spec_id])->one();

        //取到产品实例数据

  //  $model = $this->findModel($id);
        $model = new ProdInst();

        $query3 = ProdInst::find()->alias('a');
        if ($prod_spec_id==10002)
        {
            $query3->joinWith('parentProdInsts  AS g');

        }
        $query3->joinWith('regions  AS b');
        $query3->joinWith('parentRegions  AS c');


        //$query3->joinWith('superParentRegions  AS f');
        $query3->joinWith('prodAttrInsts  AS e');
        $query3->joinWith('useCusts  AS f');
        $query3->joinWith('ownCusts  AS k');

        $query3->where(['a.id' => $id ]);

        $model = $query3->one();

//        Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//           Yii::trace($model2);

        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs($prod_spec_id);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];


        $p1 = $this->getProdAttrInstByID($id );


        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;
        }

        if ($model->parentProdInsts)
        {
            $model->parentProdName = $model->parentProdInsts->prod_name;
           // Yii::trace($model->parentProdName);
        }

        $model->province        = $model->parentRegions->parent_region_id;
        $model->city             = $model->parentRegions->id;
        $model->areas            = $model->areas ;

        $model->localProdAttrsInsts=[];
        foreach($model->prodAttrInsts as $prodAttrInst)
        {
            $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
            $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
            $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
        }

//        foreach ( $model2 as $prodinst)
//        {
//
//            $model->parent_id     = $prodinst->own_cust_id;
//            $model->parent_id     = $prodinst->parent_id;
//            $model->id             = $prodinst->id ;
//            $model->prod_spec_id = $prodinst->prod_spec_id ;
//            $model->prod_name    = $prodinst->prod_name ;
//            $model->province     = $prodinst->parentRegions->parent_region_id;
//            $model->city          = $prodinst->parentRegions->id;
//            $model->areas         = $prodinst->areas ;
//            $model->region_id       = $prodinst->region_id ;
//            $model->state       = $prodinst->state ;
//            if ($prodinst->parentProdInsts)
//            {
//                $model->parentProdName = $prodinst->parentProdInsts->prod_name;
//                Yii::trace($model->parentProdName);
//            }
//
//            $model->localProdAttrsInsts=[];
//            foreach($prodinst->prodAttrInsts as $prodAttrInst)
//            {
//                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
//                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
//                $model->localProdAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
//            }
//
//           // $model->useCusts = $prodinst->useCusts;
//
//            break;
//        }



        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {
            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;

            //更新prod_inst
            $this->insertOrUpdateToProdInstTable($postModel, $model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
           // return Yii::$app->request->getReferrer();
          //  return $this->redirect( Yii::$app->request->hostInfo . $last_url);
            return $this->redirect( urldecode($last_url) );


        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        //$regionList      = $query2->orderBy('id')->all();


        //获取父级产品规格，如果没有返回0
        $parent_prod_spec_id = $this->getParentProdSpecID($prod_spec_id);

        // 获取产品状态
        $domainTypes   = Functions::getDomains('prod', 'floor.state');


        return $this->renderAjax('update',
            [
                'domainTypes' => $domainTypes,
                'parent_prod_spec_id' => $parent_prod_spec_id,
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    public function getAttrSpecs($prod_spec_id)
    {
        $attrSpecRela = ProdAttrSpecRela::find()->alias('f');
        $attrSpecRela->joinWith('attrSpecs  AS g');
        $attrSpecs    = $attrSpecRela->where(['f.prod_spec_id' => $prod_spec_id ])->all();
        return $attrSpecs;
    }






    /*
     * 为房源设置父类别，也就是楼盘，进入楼盘列表页
     * */
    public function actionSelectParent($prod_spec_id=null, $parent_id  = null)
    {

    }

//    public function actionClassify($prod_spec_id=null, $parent_id  = null)
//    {
//
//    }

    public function actionTime()
    {
        return $this->renderPartial('time', ['time' => date('H:i:s')]);

    }

    public function actionUpdateLimit()
    {
        $pk       = Yii::$app->request->post('pk');
        $value   = Yii::$app->request->post('value');
        $name      = Yii::$app->request->post('name');

        // 根据查出来的id
        $staffRela = StaffRela::find()->where(['id'=>$pk ])->one();

        $staff = Staff::find()->where(['user_id'=>$staffRela->sub_user_id])->one();
        $staff->cust_limit = $value;
        $staff->save();

        //


        //
        return $value;
    }

    /*
     * @p prod_spec_id 产品规格
     *
     * */
    public function actionIndex()
    {


        // 1.1获取自己的user_id
        $user_id = Yii::$app->user->id;

        // 1.2 获取自身的url
        // 获取当前的url $last_url
        $now_url = Yii::$app->request->getUrl();

        // 2 .1 获取绑定的模型
        $searchModel = new StaffRelaSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $user_id);

        // 将值摄入并展示


        // classify

        return $this->render('index',
            [
                'now_url'  => $now_url,
                'dataProvider' => $dataProvider,
                'searchModel' =>  $searchModel,
              ]);

    }

    // 创建子集
    //public function actionCreateSub($region_type_id=null,$region_type_name=null)

    public function actionCreate($prod_spec_id=null, $parent_prod_id = null,$last_url=null ,$yw2=null)
    {

//        $prod_spec_id   = Yii::$app->request->post('id', $prod_spec_id);
//        $parent_prod_id = Yii::$app->request->post('parent_prod_id', $parent_prod_id);
//        $last_url       = Yii::$app->request->post('last_url', $last_url);

        // 初始化类型
        $model = new ProdInst();

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
//            Yii::trace("=====================              ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);
            if (!$model->own_cust_id )
            {
                $model->own_cust_id = 0;
            }


            // 如果是房源且没有指定房源名称的话使用楼盘+房号的方式进行自动生成

            if( $model->prod_name==null){

                $model->prod_name = $model->parentProdName . $model->localProdAttrsInsts[4]['content'];
            }

           // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
        //    $model->state               = 'ON';

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToProdInstTable($model);
            return $this->redirect(urldecode($last_url));
           //return $this->redirect($last_url);

        //    return Yii::$app->request->getReferrer();
          //  return $this->redirect(['classify','prod_spec_id' =>$prod_spec_id]);
           // return   $this->redirect(Yii::app()->request->urlReferrer);
           // return  $this->redirect(Yii::$app->request->getReferrer());
            //return $this->redirect(['classify', 'region_type_id' => $region_type_id, 'region_type_name' => $region_type_name]);
        }

        // 查询所有该产品的特性规格
        $attrSpecs    = $this->getAttrSpecs($prod_spec_id);

        $attrSpecRela = ProdInst::find()->alias('f');//商圈
        $attrSpecsd    = $attrSpecRela->where(['f.prod_spec_id' => 10003 ])->all();
        //$model=ArrayHelper::map($attrSpecsd,'id','prod_name');

        Yii::trace("===================== +++++++++++++++++++++             ============");
        Yii::trace($attrSpecsd);
        Yii::trace($attrSpecsd->prod_name);

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];


        //处理初始化的父类别名称 ,有父编码的使用父编码 无父编码的使用null
        if ($parent_prod_id)
        {
            $query = ProdInst::find()->alias('a');
            $parentModel = $query->where(['a.id' => $parent_prod_id ])->One();
            $model->parentProdName = $parentModel->prod_name;
            $model->parent_id      = $parentModel->id;
            $parent_prod_spec_id    = $parentModel->prod_spec_id;
            Yii::trace($parentModel);
        }
        else
        {
            $model->parentProdName = "";
            //获取父级产品规格，如果没有返回0
            $parent_prod_spec_id = $this->getParentProdSpecID($prod_spec_id);
        }


        Yii::trace("^^^^^XXXXXXXXXXXXXXXparentProdNameXXXX^^^^^^^^^^");
        Yii::trace($model->parentProdName);

      //  $model->ownCustName = "";
      //  $parentModel = new ProdInst();

// 获取产品状态
        $domainTypes   = Functions::getDomains('prod', 'floor.state');


        // 初始化全部的图片
        $uploadModel = new UploadForm();
        return $this->renderAjax('create',
                            [
                                'domainTypes' => $domainTypes,
                                'parent_prod_id' => $parent_prod_id,
                                'parent_prod_spec_id' => $parent_prod_spec_id ,
                                'p1' =>$p1,
                                'model' => $model,
                                'uploadModel' => $uploadModel,
                                'prod_spec_id' =>$prod_spec_id,
                                'attrSpecs' => $attrSpecs,
                                'regionList' =>$regionList,
                                ]);


    }

    public function actionCreate2($prod_spec_id=null, $parent_prod_id = null,$last_url=null ,$yw2=null)
    {


        // 初始化类型
        $model = new ProdInst();


        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
//            Yii::trace("=====================         +++++++++++++++++++++++       ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);
//
//            Yii::trace($_POST['Cust']['cust_name']);
//            Yii::trace($_POST['Cust']['phone']);

            $query = CustExternalAttr::find()->alias('a');
            $query->where(['a.content' => $_POST['Cust']['phone'] , 'a.attr_spec_id' => 3]);
            $sum = $query->count();
            if($sum>=1){

            }else{
                //没有就插入数据
                $model3=new Cust();

                $model3->cust_name         = $_POST['Cust']['cust_name'] ;
                $model3->cust_type_id      = 102 ;
                $model3->create_date       = date("Y-m-d H:i:s",time()) ;
                $model3->create_staff_id   = Yii::$app->user->id;
                $model3->modify_staff_id   = Yii::$app->user->id;
                $model3->modify_date       = date("Y-m-d H:i:s",time()) ;
                $model3->state              = 301 ;
                $model3->cust_source_id     = 62 ;
                $model3->remark              = '房东' ;

                $model3->save();

                // 获得返回的id
                $id = $model3->attributes['id'];

                $model4=new CustExternalAttr();
                $model4->cust_id         = $id ;
                $model4->attr_spec_id    = 3 ;
                $model4->content         = $_POST['Cust']['phone'] ;
                $model4->save();

                $model4=new CustExternalAttr();
                $model4->cust_id         = $id ;
                $model4->attr_spec_id    = 10 ;
                $model4->content         = $_POST['Cust']['cust_name'] ;
                $model4->save();

            }



            if (!$model->own_cust_id )
            {
                $model->own_cust_id = 0;
            }


            // 如果是房源且没有指定房源名称的话使用楼盘+房号的方式进行自动生成

            if( $model->prod_name==null){

                $model->prod_name = $model->parentProdName . $model->localProdAttrsInsts[4]['content'];
            }

            // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            //    $model->state               = 'ON';

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToProdInstTable($model);
            return $this->redirect(urldecode($last_url));

        }


        $attrSpecs    = $this->getAttrSpecs(10002);

        $attrSpecsd    = $this->getAttrSpecs(10001);



        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];


        //处理初始化的父类别名称 ,有父编码的使用父编码 无父编码的使用null
        if ($parent_prod_id)
        {
            $query = ProdInst::find()->alias('a');
            $parentModel = $query->where(['a.id' => $parent_prod_id ])->One();
            $model->parentProdName = $parentModel->prod_name;
            $model->parent_id      = $parentModel->id;
            $parent_prod_spec_id    = $parentModel->prod_spec_id;
            Yii::trace($parentModel);
        }
        else
        {
            $model->parentProdName = "";
            //获取父级产品规格，如果没有返回0
            $parent_prod_spec_id = $this->getParentProdSpecID($prod_spec_id);
        }

//
//        Yii::trace("^^^^^XXXXXXXXXXXXXXXparentProdNameXXXX^^^^^^^^^^");
//        Yii::trace($model->parentProdName);


// 获取产品状态
        $domainTypes   = Functions::getDomains('prod', 'floor.state');

        $model2 = new Cust();

        // 初始化全部的图片
        $uploadModel = new UploadForm();
        return $this->renderAjax('create',
            [
                'domainTypes' => $domainTypes,
                'parent_prod_id' => $parent_prod_id,
                'parent_prod_spec_id' => $parent_prod_spec_id ,
                'p1' =>$p1,
                'model' => $model,
                'model2' => $model2,
                'uploadModel' => $uploadModel,
                'prod_spec_id' =>$prod_spec_id,
                'attrSpecs' => $attrSpecs,
                'attrSpecsd' => $attrSpecsd,
                'regionList' =>$regionList,
                'yw2'=>$yw2]);


    }


    public function actionSite($parent_region_id=null)
    {

        $query = new Region();
        $model = $query->getCityList($parent_region_id);

        echo Html::tag('option','选择区域', ['value'=>'empty']) ;
        foreach($model as $value=>$name)
        {
            echo Html::tag('option',Html::encode($name),array('value'=>$value));
        }


    }

    public function actionDelete($id, $prod_spec_id=null, $last_url=null)
    {

        try{
            $this->deleteProdInst($id);
           // Yii::$app->getAuthManager()->remove($model->item);
            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
        }catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '删除失败.'));
          //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        return $this->redirect(urldecode($last_url));
    }

    public function deleteProdInst($id)
    {
        $prodInst = ProdInst::find()->where(['id'=>$id])->one();
        if($prodInst)$prodInst->delete();
    }


    /*通过prod-id获取全部的产品属性实例*/
    public function  getProdAttrInstByID($prod_id=null )
    {
        // 初始化最重要的产品实例字段
        //$model = new ProdAttrInst();
        $model=[];
        $query = ProdAttrInst::find()->alias('a');
        $query->joinWith('attrSpecs  AS b');
        $query->joinWith('images  AS c');


        $query->where(['a.prod_id' => $prod_id , 'b.attr_spec_type_id' => 2]);
        $models = $query->all();

        foreach ($models as $key => $values)
        {
            $model[$values->attrSpecs['attr_spec_id']][] = $values->images['url'] . $values->images['image_name'];
        }

        return $model;
    }



    public function getSubProdSpecID($prod_spec_id=null)
    {
        $prodSpec = ProdSpec::find()->select(['prod_spec_id'])->where(['parent_prod_spec_id' => $prod_spec_id])->one();
//        Yii::trace("+++++++++++++++++++++++++++++++++++++++++++++");
//
//        Yii::trace($prodSpec);

        return $prodSpec->prod_spec_id;
    }

    public function getParentProdSpecID($prod_spec_id=null)
    {
        $prodSpec = ProdSpec::find()->select(['parent_prod_spec_id'])->where(['prod_spec_id' => $prod_spec_id])->one();


        return $prodSpec->parent_prod_spec_id;
    }

    /*获取房源数组*/
    public function getAllFloors($parent_id )
    {
        $allFloors=[];

        $model = new ProdInst();


        $query = ProdInst::find()->alias('a');

        $query->where(['a.parent_id' => $parent_id ]);
        $query->joinWith('prodAttrInsts  AS e');
        $query->joinWith('useCusts  AS f');
        $models = $query->all();



        foreach ( $models as $model)
        {
            $floor     = 0;
            $totalArea = 0;
            $room      = "";

            // 找出楼层， 汇总楼层平方数
            foreach($model->prodAttrInsts as $prodAttrInst)
            {

                if ($prodAttrInst->attr_spec_id==14)
                {
                    $floor = $prodAttrInst->content;
                }

                if ($prodAttrInst->attr_spec_id==8)
                {
                    $totalArea = $prodAttrInst->content;
                }

                 if ($prodAttrInst->attr_spec_id==4)
                 {
                     $room = $prodAttrInst->content;
                 }
            }
            $allFloors[$floor]['floor'] = $floor;
            $allFloors[$floor]['totalArea'] += $totalArea;

            // 先判断是不是有这个用户
            if ($allFloors[$floor]['custs'][$model->useCusts->cust_name] && $model->useCusts->cust_name){

                $index = $allFloors[$floor]['custs'][$model->useCusts->cust_name]['index'];

                $allFloors[$floor]['rooms'][$index]['room'] .=  ' ' . $room;
                $allFloors[$floor]['rooms'][$index]['area']  += $totalArea;
                $allFloors[$floor]['rooms'][$index]['length']++;
             //   $allFloors[$floor]['rooms'][$index]['state'] = $model->state;
              //  $allFloors[$floor]['rooms'][$index]['cust_name'] = $model->useCusts->cust_name;
            //    $allFloors[$floor]['rooms'][$index]['id'] = $model->id;
             //   $allFloors[$floor]['rooms'][$index]['prod_spec_id'] = $model->prod_spec_id;
            }
            else{
                // 按照名字记录索引
                $allFloors[$floor]['custs'][$model->useCusts->cust_name]['index'] = $room;

                $allFloors[$floor]['rooms'][$room]['room'] = $room;
                $allFloors[$floor]['rooms'][$room]['area']  = $totalArea;
                $allFloors[$floor]['rooms'][$room]['state'] = $model->state;
                $allFloors[$floor]['rooms'][$room]['cust_name'] = $model->useCusts->cust_name;
                $allFloors[$floor]['rooms'][$room]['id'] = $model->id;
                $allFloors[$floor]['rooms'][$room]['prod_spec_id'] = $model->prod_spec_id;
                $allFloors[$floor]['rooms'][$room]['length']=1;
            }



//            $allFloors[$floor]['rooms'][$room]['room'] = $room;
//            $allFloors[$floor]['rooms'][$room]['area']  = $totalArea;
//            $allFloors[$floor]['rooms'][$room]['state'] = $model->state;
//            $allFloors[$floor]['rooms'][$room]['cust_name'] = $model->useCusts->cust_name;
//            $allFloors[$floor]['rooms'][$room]['id'] = $model->id;
//            $allFloors[$floor]['rooms'][$room]['prod_spec_id'] = $model->prod_spec_id;


        //    Yii::trace("+_+_+_+_+_+_+___________________________++++++++++");
         //   Yii::trace($model->useCusts->cust_name);

        }

        foreach($allFloors as $key => $floors )
        {
            foreach($floors['rooms'] as $room_id =>$room)
            {
                if ($room['length']>6){
                    $allFloors[$key]['rooms'][$room_id]['length'] = 6;
                }elseif  (count($floors['rooms'])<=3)
                {
                    $allFloors[$key]['rooms'][$room_id]['length'] = $allFloors[$key]['rooms'][$room_id]['length']*2;
                }
            }
        }


        return $allFloors;
    }

    /*通过prod-id获取全部的产品实例*/
    public function getProdInst($id=null)
    {
        // 初始化最重要的产品实例字段
        $model = new ProdInst();


        $query = ProdInst::find()->alias('a');
        $query->joinWith('users  AS f');
        $query->joinWith('modifyUsers  AS g');
        $query->joinWith('regions  AS b');
        $query->joinWith('parentRegions  AS c');
        $query->joinWith('prodAttrInsts  AS e');
        $query->where(['a.id' => $id ]);
        $models = $query->all();

//        $model
//        $models->province     = $models->parentRegions->parent_region_id;
//        $models->city          = $models->parentRegions->id;
//        foreach($models->prodAttrInsts as $attrSpec)
//        {
//            $models->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
//        }
//
//        return $models;
        $model = $models[0];
        foreach($models[0]->prodAttrInsts as $attrSpec)
        {
            $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
        }

//        foreach ( $models as $prodinst)
//        {
//           // Yii::trace("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
//            $model->id             = $prodinst->id ;
//            $model->prod_spec_id = $prodinst->prod_spec_id ;
//            $model->prod_name    = $prodinst->prod_name ;
//
//
//
//            $model->areas         = $prodinst->areas ;
//            $model->region_id    = $prodinst->region_id ;
//
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//            $model->region_id    = $prodinst->region_id ;
//
//
//            $model->province     = $prodinst->parentRegions->parent_region_id;
//            $model->city          = $prodinst->parentRegions->id;
//
//            foreach($prodinst->prodAttrInsts as $attrSpec)
//            {
//                $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
//            }
//
//            break;
//        }

        return $model;
    }

    // 获取商圈所属楼盘总面积
    public function getTotalAreas($tradingAreaID = null, $parent_prod_spec_id=null)
    {



        $sql  = 'SELECT sum(truncate(content,2)) as sumTotalArea FROM  ';
        $sql .= ProdAttrInst::tableName();
        $sql .= ' as a, ';
        $sql .= ProdInst::tableName() ;
        $sql .= ' as b ';

        //如果有父值，需要使用父值进行限定查询
        if ($tradingAreaID)
        {
            // 如果是楼盘，需要查询两层 ，如果是楼房只需要查询一层
            if ($parent_prod_spec_id==10004)
            {
                $sql .= ' , ';
                $sql .= ProdInst::tableName() ;
                $sql .= ' as c ';
                $sql .=  ' WHERE c.id = b.parent_id and c.parent_id=:parent_id and a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id   ';
                $lendedAreas = Yii::$app->db->createCommand($sql)
                ->bindValue(':parent_id',$tradingAreaID)
                ->bindValue(':attr_spec_id', 8)
                ->bindValue(':prod_spec_id','10002')

                ->queryOne();
            }
            else
            {
                $sql .=  ' WHERE b.parent_id=:parent_id and a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id   ';
                $lendedAreas = Yii::$app->db->createCommand($sql)
                    ->bindValue(':parent_id',$tradingAreaID)
                    ->bindValue(':attr_spec_id', 8)
                    ->bindValue(':prod_spec_id','10002')

                    ->queryOne();
            }
            //$sql .= ProdInst::tableName() ;
            //$sql .= ' as c ';

        }
        else
        {
            $sql .=  ' WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id   ';
            $lendedAreas = Yii::$app->db->createCommand($sql)
                ->bindValue(':attr_spec_id', 8)
                ->bindValue(':prod_spec_id','10002')

                ->queryOne();
        }

//        if ()
//        {
//            $sql .= ProdInst::tableName() ;
//            $sql .= ' as c ';
//        }



        $sumTotalArea = $lendedAreas['sumTotalArea'];
        if ($sumTotalArea)
        {
            return $sumTotalArea;
        }
        $sumTotalArea = 0;

        return $sumTotalArea;
    }

    // 获取商圈所属楼盘已租面积
    public function getTotalLendedAreas($tradingAreaID=null)
    {
        //数据初始化
        $sumContent = 0;
        // 先取出父id对应的规格标识
        $query = ProdInst::find()->alias('f');


        $parentProdInst  = $query->where(['f.id' => $tradingAreaID ])->one();

        $sql  = 'SELECT sum(truncate(content,2)) as sumContent FROM  ';
        $sql .= ProdAttrInst::tableName();
        $sql .= ' as a, ';
        $sql .= ProdInst::tableName() ;

        if($parentProdInst->prod_spec_id==10004){


            $sql .= ' as b, ';
            $sql .= ProdInst::tableName() ;
            $sql .= ' as c WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.parent_id = c.id and   b.prod_spec_id = :prod_spec_id and b.state = :state and c.parent_id=:parent_id ';


        }
        else {

            $sql .= ' as b WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and b.state = :state and b.parent_id=:parent_id ';

        }

        $lendedAreas = Yii::$app->db->createCommand($sql)
            ->bindValue(':attr_spec_id', 8)
            ->bindValue(':prod_spec_id', '10002')
            ->bindValue(':state', '1002')
            ->bindValue(':parent_id', $tradingAreaID)
            ->queryOne();
        $sumContent = $lendedAreas['sumContent'];


        if ($sumContent)
        {
            return $sumContent;
        }
        $sumContent = 0;

        return $sumContent;

    }



    // 获取可招商面积
    public function getTotalAttractAreas($tradingAreaID = null, $parent_prod_spec_id=null)
    {
        $sql = 'SELECT sum(truncate(c.content,2)) as sumAttract FROM  ';
        $sql .= ProdAttrInst::tableName();
        $sql .= ' as a, ';
        $sql .= ProdInst::tableName();
        $sql .= ' as b, ';
        $sql .= ProdAttrInst::tableName();


        //如果有父值，需要使用父值进行限定查询
        if ($tradingAreaID) {
            // 如果是楼盘，需要查询两层 ，如果是楼房只需要查询一层
            if ($parent_prod_spec_id == 10004) {

                $sql .= ' as c, ';

                $sql .= ProdInst::tableName() ;
                $sql .= ' as d ';

                $sql .=' WHERE d.id = b.parent_id and d.parent_id = :parent_id and  a.attr_spec_id = :attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and a.content = :content and c.attr_spec_id = :attr_spec_id_k and c.prod_id = b.id';
                $attractAreas = Yii::$app->db->createCommand($sql)
                    ->bindValue(':parent_id', $tradingAreaID)
                    ->bindValue(':attr_spec_id', '9')
                    ->bindValue(':prod_spec_id', '10002')
                    ->bindValue(':content', '4001')
                    ->bindValue(':attr_spec_id_k', '8')
                    ->queryOne();

            }
            else{

                $sql .= ' as c WHERE b.parent_id = :parent_id and a.attr_spec_id = :attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and a.content = :content and c.attr_spec_id = :attr_spec_id_k and c.prod_id = b.id';
                $attractAreas = Yii::$app->db->createCommand($sql)
                    ->bindValue(':parent_id', $tradingAreaID)
                    ->bindValue(':attr_spec_id', '9')
                    ->bindValue(':prod_spec_id', '10002')
                    ->bindValue(':content', '4001')
                    ->bindValue(':attr_spec_id_k', '8')
                    ->queryOne();

            }

        }
        else
        {
            $sql .= ' as c WHERE a.attr_spec_id = :attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and a.content = :content and c.attr_spec_id = :attr_spec_id_k and c.prod_id = b.id';
            $attractAreas = Yii::$app->db->createCommand($sql)
                ->bindValue(':attr_spec_id', '9')
                ->bindValue(':prod_spec_id', '10002')
                ->bindValue(':content', '4001')
                ->bindValue(':attr_spec_id_k', '8')
                ->queryOne();
        }





        $sumAttract = $attractAreas['sumAttract'];
        if ($sumAttract)
        {
            return $sumAttract;
        }
        $sumAttract = 0;

        return $sumAttract;
    }

    // 获取在租房源均价
    public function getTotalLendedPrices($tradingAreaID=null, $prod_spec_id=null)
    {



        $sql  = 'SELECT truncate(sum(truncate(content,2))/count(*),2) as sumLendedPrices FROM  ';
        $sql .= ProdAttrInst::tableName();
        $sql .= ' as a, ';
        $sql .= ProdInst::tableName() ;

        if ($prod_spec_id==10004)
        {
            $sql .= ' as b, ';
            $sql .= ProdInst::tableName() ;
            $sql .= ' as c WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.parent_id=c.id and b.prod_spec_id = :prod_spec_id and b.state = :state and c.parent_id = :parent_id  ';
        }
        else
        {
            $sql .= ' as b WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and b.state = :state and b.parent_id = :parent_id  ';
        }

        $lendedPrices = Yii::$app->db->createCommand($sql)
            ->bindValue(':attr_spec_id', 7)
            ->bindValue(':prod_spec_id','10002')
            ->bindValue(':state', '1002')
            ->bindValue(':parent_id', $tradingAreaID)
            ->queryOne();

        $sumLendedPrices = $lendedPrices['sumLendedPrices'];
        if ($sumLendedPrices)
        {
            return $sumLendedPrices;
        }
        $sumLendedPrices = 0;

        return $sumLendedPrices;

    }

    // 获取全部入住的企业
    public function getTotalUseCustCount($tradingAreaID=null, $prod_spec_id=null)
    {
//        $sql  = 'SELECT use_cust_id FROM  ';
//        $sql .= ProdInst::tableName();
//        $sql .= ' as a  WHERE prod_spec_id=:prod_spec_id and state=:2 and use_cust_id is not null GROUP BY use_cust_id';
//
//        $useCustCount = Yii::$app->db->createCommand($sql)
//            ->bindValue(':prod_spec_id' ,'10002')
//            ->bindValue(':2', '1002')
//            ->query()->rowCount;
//
//        return $useCustCount;

        $sql  = 'SELECT a.use_cust_id FROM  ';
        $sql .= ProdInst::tableName();

        if ($prod_spec_id==10002)
        {
            $sql .= ' as a  WHERE  id=:1 and state=:2 and use_cust_id is not null GROUP BY use_cust_id';
        }
        elseif ($prod_spec_id==10004)
        {
            $sql .= ' as a, ';
            $sql .= ProdInst::tableName() ;
            $sql .= ' as b  WHERE b.parent_id=:1 and a.parent_id = b.id and a.state=:2 and a.use_cust_id is not null GROUP BY a.use_cust_id';
        }

        else{
            $sql .= ' as a  WHERE parent_id=:1 and state=:2 and use_cust_id is not null GROUP BY use_cust_id';
        }


        $useCustCount = Yii::$app->db->createCommand($sql)
            ->bindValue(':1', $tradingAreaID)
            ->bindValue(':2', '1002')
            ->query()->rowCount;

        return $useCustCount;
    }

    // 取出父级区域编码对应的文字
    public function getParentRegionTypes($parent_region_id)
    {
        $query2 = Region::find();
        $query2->where(['parent_region_id' => $parent_region_id ]);
        $regionList      = $query2->orderBy('id')->all();
        return $regionList;
    }

    // 取出区域编码对应的文字
    public function getRegionTypes()
    {

        $regionTypes = [];
        $query = RegionType::find()->alias('a');
        $queryRegionTypes = $query->all();
        foreach ($queryRegionTypes as $queryRegionType)
        {
            $regionTypes[$queryRegionType->id] = $queryRegionType->region_type_name;
        }

        return $regionTypes;
    }


    public function saveFile($file)
    {
        $url = 'uploads/';
        $filelName =  time().rand(100,999) . '.' . $file->extension;
        $file->saveAs($url . $filelName);

        // 将图片地址存入数据库，记录该图片的来源时间和上传人
        $image                = new Image();
        $image->image_name  = $filelName;
        $image->url          = '/' . $url;
        $image->create_date = date("Y-m-d H:i:s",time());
        $image->staff_id     = Yii::$app->user->id;

        $image->save();

        // 获得id
        $imageId = $image->attributes['id'];

        return $imageId;
    }
    /**
     * 新增或者修改 role table
     * @param $newRole
     * @param string $oldRole
     */
    public function insertOrUpdateToProdInstTable( $newProdInst, $oldProdInst=null)
    {
        $i = 0;                   // 批量插入的数量
        $insertProdAttrs =[];     // 批量插入的数组
        $oldProdAttrInst = [];  // 旧的产品特性实例

        //$should = 0;//1=insert,2=update,0=nothing to do
        //$role   = null;
        if($oldProdInst)
        {
          //  Yii::trace("************************************************************");
        //    Yii::trace($newProdInst);


            $prodInst = ProdInst::find()->where(['id'=>$newProdInst->id])->one();

            $prodInst->modify_date        = date("Y-m-d H:i:s",time());;
            $prodInst->modify_staff_id   = Yii::$app->user->id;
            $prodInst-> prod_name         = $newProdInst->prod_name;
            $prodInst-> prod_spec_id     = $newProdInst->prod_spec_id;
            $prodInst-> parent_id         = $newProdInst->parent_id;
            $prodInst-> region_id         = $newProdInst->region_id ;
            $prodInst-> price_id          = $newProdInst->price_id ;
            $prodInst-> own_cust_id       = $newProdInst->own_cust_id ;
            $prodInst-> use_cust_id       = $newProdInst->use_cust_id ;
            $prodInst-> state              = $newProdInst->state ;

            $prodInst->save();



            // 填写产品特性值
            // 检查产品特性值是否有值，或者有变化， 有变化就更新，原来没有值插入值

            // 构成标准值
            foreach ($prodInst->prodAttrInsts as $key => $prodAttrInst)
            {
                $oldProdAttrInst[$prodAttrInst->attr_spec_id]['content'] = $prodAttrInst->content;
                $oldProdAttrInst[$prodAttrInst->attr_spec_id]['id']       = $prodAttrInst->id;
            }
//            Yii::trace("********************************************");
//            Yii::trace($newProdInst);



            if ($newProdInst->localProdAttrsInsts){
                foreach ($newProdInst->localProdAttrsInsts as $key => $prodAttrInst)
                {
                    // 如果实例不存在则新增
                    if (!$oldProdAttrInst[$key])
                    {
                        //  Yii::trace("#############################################");
                        //处理图片类型
                        if ($prodAttrInst['attrSpecTypeID']==2)
                        {
                            // 初始化图片对象类
                            $uploadModel = new UploadForm();

                            //取出对应的图片句柄
                            $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');



                            // 审核是否有图片 & 图片是否符合校验标准
                            if ($uploadModel->file  && $uploadModel->validate())
                            {
                                $imageIndex = 0;

                                // 将图片插入表格
                                foreach ($uploadModel->file as $file)
                                {
//                                Yii::trace("===============================");
//                                Yii::trace($file->baseName);

//                                $url = 'uploads/';
//                                $filelName =  time().rand(100,999) . '.' . $file->extension;
//                                $file->saveAs($url . $filelName);
//
//                                // 将图片地址存入数据库，记录该图片的来源时间和上传人
//                                $image                = new Image();
//                                $image->image_name  = $filelName;
//                                $image->url          = '/' . $url;
//                                $image->create_date = date("Y-m-d H:i:s",time());
//                                $image->staff_id     = Yii::$app->user->id;
//
//                                $image->save();
//                                $image->attributes['id']
                                    // 获得id
                                    $imageId =  $this->saveFile($file) ;

                                    if ($imageId)
                                    {
                                        $insertProdAttrs[$i][] = $prodInst->id;
                                        $insertProdAttrs[$i][] = $key;
                                        $insertProdAttrs[$i][] = $imageId ;
                                        $insertProdAttrs[$i][] = $imageIndex ;

                                        $i++;
                                        $imageIndex++;
                                    }



                                    // 构成属性值的更新或者插入语句
                                }

                            }
                        }
                        else
                        {
                            // 如果值为空也不插入
                            if(!$prodAttrInst['content'])
                            {
                                continue;
                            }

                            $content = $prodAttrInst['content'] ;

                            $insertProdAttrs[$i][] = $prodInst->id;
                            $insertProdAttrs[$i][] = $key;
                            $insertProdAttrs[$i][] = $prodAttrInst['content'] ;
                            $insertProdAttrs[$i][] = 0 ;
                            $i++;
                        }






                    }
                    else//存在的话看下数值是否一致，不一致则更新
                    {
                        if ($prodAttrInst['attrSpecTypeID']==2)
                        {
                            // 初始化图片对象类
                            $uploadModel = new UploadForm();

                            //取出对应的图片句柄
                            $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');



                            // 审核是否有图片 & 图片是否符合校验标准
                            if ($uploadModel->file  && $uploadModel->validate())
                            {
                                $imageIndex = 0;

                                // 将图片插入表格
                                foreach ($uploadModel->file as $file)
                                {
//                                Yii::trace("===============================");
//                                Yii::trace($file->baseName);

//                                $url = 'uploads/';
//                                $filelName =  time().rand(100,999) . '.' . $file->extension;
//                                $file->saveAs($url . $filelName);
//
//                                // 将图片地址存入数据库，记录该图片的来源时间和上传人
//                                $image                = new Image();
//                                $image->image_name  = $filelName;
//                                $image->url          = '/' . $url;
//                                $image->create_date = date("Y-m-d H:i:s",time());
//                                $image->staff_id     = Yii::$app->user->id;
//
//                                $image->save();
//                                $image->attributes['id']
                                    // 获得id
                                    $imageId =  $this->saveFile($file) ;

                                    if ($imageId)
                                    {
                                        ProdAttrInst::updateAll(['content' => $imageId], ['id' => $oldProdAttrInst[$key]['id']]);


                                    }



                                    // 构成属性值的更新或者插入语句
                                }

                            }
                        }
                        else
                        {
                            if ($oldProdAttrInst[$key]['content']!=$prodAttrInst['content'])
                            {
                                ProdAttrInst::updateAll(['content' => $prodAttrInst['content']], ['id' => $oldProdAttrInst[$key]['id']]);
//.                        $model = ProdAttrInst::findOne($oldProdAttrInst[$key]['id']);
//                        $model->content = $content;
//                        $count = $model->update(array('content'));
                            }

                        }
                        //


                    }

                }
            }




        }
        else
        {



            $newProdInst->save();

            // 获得产品id
            $id = $newProdInst->attributes['id'];


            // 新增的话需要生成订单 ，先检查传入的员工号 orderStaffID
            // 暂时掠过校验
            // 插入订单和订单流水

            // 初始化类型
            $orderModel        = new Order();


            $orderModel->staff_id          = $newProdInst->orderStaffID;
            $orderModel->object_id         = $id;
            $orderModel->state              = 30001;
            $orderModel->object_type_id    = 2;  // 楼盘
            $orderModel->order_type_id     = 2;  // 楼盘放租
            $orderModel->modify_staff_id   = Yii::$app->user->id;
            $orderModel->create_staff_id   = Yii::$app->user->id;
            $orderModel->create_date        = date("Y-m-d H:i:s",time());
            $orderModel->modify_date        = date("Y-m-d H:i:s",time());
            $orderModel->remark              = $newProdInst->orderRemark;

            $orderModel->save();

            $ordrId = $orderModel->attributes['id'];

            $orderResumesModel = new OrderResumes();

            $orderResumesModel->order_id           = $ordrId;
            $orderResumesModel->staff_id           = $newProdInst->orderStaffID;
            $orderResumesModel->resumes_type_id   = 20001;
            $orderResumesModel->create_staff_id   = Yii::$app->user->id;
            $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
            $orderResumesModel->remark              = $newProdInst->orderRemark;
            $orderResumesModel->last_state          = 30004;
            $orderResumesModel->next_state          = $orderModel->state;

            $orderResumesModel->save();



            if ($newProdInst->localProdAttrsInsts) {


                foreach ($newProdInst->localProdAttrsInsts as $key => $prodAttrInst) {


                    //  Yii::trace("#############################################");
                    //处理图片类型
                    if ($prodAttrInst['attrSpecTypeID'] == 2) {
//                                  Yii::trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
//                     Yii::trace($key);


//                    Yii::trace($image);

                        // 初始化图片对象类
                        $uploadModel = new UploadForm();

                        //取出对应的图片句柄
                        $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');

                        // 审核是否有图片 & 图片是否符合校验标准
                        if ($uploadModel->file && $uploadModel->validate()) {
                            $imageIndex = 0;

                            // 将图片插入表格
                            foreach ($uploadModel->file as $file) {
                                // 获得id
                                $imageId = $this->saveFile($file);

                                $insertProdAttrs[$i][] = $id;
                                $insertProdAttrs[$i][] = $key;
                                $insertProdAttrs[$i][] = $imageId;
                                $insertProdAttrs[$i][] = $imageIndex;

                                $i++;
                                $imageIndex++;

                                // 构成属性值的更新或者插入语句
                            }

                        }

                        continue;
                    }

                    // 如果值为空也不插入
                    if (!$prodAttrInst['content']) {
                        continue;
                    }

                    $content = $prodAttrInst['content'];

                    $insertProdAttrs[$i][] = $id;
                    $insertProdAttrs[$i][] = $key;
                    $insertProdAttrs[$i][] = $content;
                    $insertProdAttrs[$i][] = 0;
                    $i++;

                }

            }
//            $prodAttrInst = new ProdAttrInst();
//            $prodAttrInst->prod_id = $id;
            //将属性插入产品属性实例表
        }

        // 如果插入数组不为空则执行插入
        if (!empty($insertProdAttrs))
        {
            Yii::$app->db->createCommand()->batchInsert(ProdAttrInst::tableName(), ['prod_id','attr_spec_id','content','sort'], $insertProdAttrs)->execute();
        }



    }

//    public function actionIndex()
//    {
//        $menus = SystemEvent::GetAdminMenu();
//        if(Yii::$app->request->isAjax){
//            return '<script>OA_Menus='.Json::encode($menus).'</script>';
//        }
//        return $this->renderPartial('index',['menus'=>$menus]);
//    }


    public function actionRepeatorder($tel=null)
    {
        $results    = [];
        // 使用json返回
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $whereCust['a.attr_spec_id'] = 4;
        $whereCust['a.content'] = $tel;

        // 先取ProdAttrInst信息，
        $query = ProdAttrInst::find()->alias('a');
        $query->joinWith('prodInsts  AS b');

        $query->where($whereCust);
        $modelCust = $query->one();

        Yii::trace("#############################################");
        Yii::trace($modelCust);


    }

    //抢单页
    public function actionCommonality($id=null, $prod_spec_id=null, $prod_spec_name = null,$last_url=null)
    {


        $model = ProdInst::find()->where(['id'=>$id])->one();


        $model->modify_staff_id  = Yii::$app->user->id;
        $model->modify_date      = date("Y-m-d H:i:s",time());
        $model->commonality      = Yii::$app->user->id;
        $model->save();

        $id=Yii::$app->user->id;
        return $this->redirect( ['/prod/prodinst/gonyoumng','commonality'=>$id]);

    }

    //变更负责人
    public function actionModifyuser($order_id,  $last_url = null)
    {

        // 初始化订单M
       // $postModel   = new Order();
        $postModel   = new ProdInst();


        $order = ProdInst::find()->alias('a')->where(['a.id'=>$order_id])->one();
//        Yii::trace("=============newState==================");
//        Yii::trace($order);
//        Yii::trace($order->commonality);

        $order->commonality         =  $order->commonality;


        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {

            $newState = null;

            //如果没有传入有效的u-id，则默认为转给自己
            if (!$postModel->commonality){
                $postModel->commonality = Yii::$app->user->id;
            }

            $this->updateOrder($order_id,$postModel->commonality, $postModel->remark, 20003 );

            //prodinst表commonality字段修改成别人
            $model = ProdInst::find()->where(['id'=>$order_id])->one();

            $model->modify_staff_id  = Yii::$app->user->id;
            $model->modify_date      = date("Y-m-d H:i:s",time());
            $model->commonality      = $postModel->commonality;
            $model->save();


            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            if ($last_url)
            {
                $last_url = substr($last_url,21,9);
                return $this->redirect($last_url);
            }
            else{

                // 跳回房源抢单页面
                $id=Yii::$app->user->id;
                return $this->redirect( 'gonyoumng',['commonality'=>$id]);
            }
        }

        // 获取状态domain
        // 查询订单状态的种类
        $orderStates = $this->getDomains('order','state');

        if ($order)
        {
            return $this->renderAjax('_modify_uesr_form',
                [
                    'model' => $order,
                    'orderStates' => $orderStates,
                ]);


        }

    }

    public function updateOrder($id, $user_id, $remark=null,$resumes_type_id=null, $newState=null,$reason=null,$postModel=null)
    {
        $order = Order::find()->where(['id'=>$id])->one();


        $oldState = $order->state;
        if($order)
        {
            if ($newState)
            {
                $order->state = $newState;
            }
            //如果撤单原因有值且状态变更为无效
            if ($reason && $order->state==30003)
            {
                $order->reason = $reason;
            }
            //$order->remark  =  $remark;

            $order->staff_id           = $user_id;
            $order->modify_date        = date("Y-m-d H:i:s",time());;
            $order->modify_staff_id   = Yii::$app->user->id;
            //  $order->remark              = $remark;
            $order->save();




            $orderResumesModel = new OrderResumes();

            $orderResumesModel->order_id           = $id;
            $orderResumesModel->staff_id           = $user_id;
            $orderResumesModel->resumes_type_id   = $resumes_type_id ;
            $orderResumesModel->create_staff_id   = Yii::$app->user->id;
            $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
            $orderResumesModel->remark              = $remark;
            $orderResumesModel->last_state          = $oldState ;
            $orderResumesModel->next_state          = $order->state;

            $orderResumesModel->save();
        }

    }

    /*
       *  获取订单客户域
       *
       * */
    public function getDomains($domainTableName = null, $domainFieldName = null)
    {
        $where     = []; // 查询条件
        $domainOut = []; //返回的domain数组，以code为索引，name为值的数组
        $where['domain_table_name'] = $domainTableName;
        $where['domain_field_name'] = $domainFieldName;
        $query = Domain::find();
        $domains = $query->where($where)->all();


        foreach ($domains as   $values)
        {
            $domainOut[$values->domain_code ] = $values->domain_name;
        }

        return $domainOut;
    }



}
